<template>
    <div class="common-tabs-wrap">
        <Card :padding="10" dis-hover class="no-border-card">
            <p slot="title">
                门店指导用电配置
                <Button type="ghost" class="btn-left" size="small"  @click="changeState">{{str}}</Button>
                <Button type="ghost" size="small" @click="resetAll" v-if="strFlag == 2">取消</Button>
            </p>
            <div slot="extra">
                当前门店：
                <Select v-model="store_id" filterable @on-change="selectStore" style="width: 150px;">
                    <Option v-for="item in stores" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </div>
            
            <Row>
                <Col span="12">
                    <Form ref="form1" :model="form1Data" :rules="form1Rules" :label-width="86" :show-message="false">

                        <FormItem label="门店电价" class="form-item">
                            <Select v-model="form1Data.elePriceType" style="width: 220px;" v-if="currentTab == 1" :disabled="strFlag == 1">
                                <Option v-for="item in elePriceTypes" :value="item.id" :key="item.id">{{ item.text }}</Option>
                            </Select>
                            <template v-if="form1Data.elePriceType == 2">
                            <InputNumber 
                                v-model="form1Data.storeElePrice" 
                                :min="0" 
                                :max="100" 
                                :disabled="strFlag == 1" 
                                style="width: 120px;"
                                :formatter="formatInput"/>
                            元/度
                            </template>
                        </FormItem>

                        <FormItem label="付费模式" class="form-item" prop="payMode">
                            <Select v-model="form1Data.payMode" style="width: 220px;" v-if="currentTab == 1" :disabled="strFlag == 1">
                                <Option v-for="item in payModes" :value="item.type" :key="item.type">{{ item.text }}</Option>
                            </Select>
                            <Select v-model="form1Data.storePayMode" style="width: 120px;" v-show="form1Data.payMode == 2" :disabled="strFlag == 1">
                                <Option v-for="item in storePayModes" :value="item.type" :key="item.type">{{ item.text }}</Option>
                            </Select>
                        </FormItem>

                        <FormItem label="透支额度" class="form-item" v-show="isPostPaid">
                            <InputNumber 
                                v-model="form1Data.storeOverdraft" 
                                :min="0" 
                                :max="999" 
                                :disabled="strFlag == 1 || form1Data.payMode == 1" 
                                :formatter="formatInput" style="width:220px"></InputNumber>
                            度
                        </FormItem>

                        <FormItem label="断电提醒" class="form-item" v-show="isPostPaid" >
                            <Select style="width: 220px;" v-model="form1Data.storeLowWarn" :disabled="strFlag == 1 || form1Data.payMode == 1">
                                <Option v-for="item in LowWarnValues" :value="item" :key="item">{{ item }}</Option>
                            </Select>
                            度
                        </FormItem>
                    </Form>
                </Col>
            </Row>
        </Card>

        <Card dis-hover class="no-border-card" style="margin-top:15px">
                <p slot="title">
                    房源自定义配置列表
                    <Button type="primary" 
                    class="btn-in-top-large"
                    @click="exportList">
                    导出列表
                    </Button>
                </p>

                <Table class="table" :columns="columns" :data="cfgList"/>

                <Page v-if="total" :current.sync="currPage" :total="total" :page-size="limit" :current="currPage" show-elevator show-total style="text-align:center" @on-change="onPageChange"></Page>
        </Card>

    </div>
</template>

<script>
import { ElemeterPayMode, LowWarnValues } from '@/libs/const'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
// import util from '@/libs/util';
// import validate from '@/libs/validate';

const LIMIT = 15
const ListTypes = [{ id: 1, text: '按房源查看' }, { id: 2, text: '按房间查看' }]

let _params = {
  type: 1,
  offset: 0,
  limit: LIMIT
}

export default {
  name: 'storeCfg',
  props: {
    tableHeaders: Function,
    currentTab: Number
  },

  watch: {
    // currentTab(newVal) { // 解决改变商户电价 门店电价不刷新问题
    //     if(newVal){ //只有当currentPage为门店配置中心才刷新

    //         this.elePriceTypes = []
    //         this.payModes = []
    //         this.overdraftTypes = []
    //         this.lowWarnTypes = []
    //         this.loadSettingInfo()

    //     }
    // },
    StorePayMode (newVal, oldVal) {
      if (typeof oldVal !== 'undefined') {
        // 当数据不为初始化数据
        this.currentPayType = newVal
      }
    },
    payMode (newVal, oldVal) {
      if (typeof oldVal !== 'object') {
        // 当数据不为初始化数据
        if (newVal === 1) {
          this.currentPayType = this.parentIsPostPaid ? 2 : 1
          this.form1Data.storeOverdraft = this.parentOverdraftAmountValue
          this.form1Data.storeLowWarn = this.parentLowWarnValue
        } else {
          this.currentPayType = this.StorePayMode
        }
      }
    },
    currentPayType (newVal, oldVal) {
      // 当付费模式切换的时候

      if ((typeof oldVal !== 'object' && newVal !== null) || (typeof newVal !== 'object' && oldVal !== null)) {
        this.$Modal.warning({
          title: newVal === 2 ? '预付费切换后付费' : '后付费切换预付费',
          content: '门店付费模式修改，只影响即将绑定的房间。已绑定电表的房间付费模式不同步更新。',
          // content:
          //     newVal == 2
          //         ? `<p>切换后，所有使用门店统一方案的房源及房间均会同步切换。剩余电量及充值电量将清零。为避免影响使用，建议记录相关房间数据后切换</p>`
          //         : `<p>切换后，所有使用门店统一方案的房源及房间均会同步切换。如房间剩余电量不足将自动断电。为避免影响使用，建议切换后，及时通知租客充值<p>`,
          okText: '我已知悉'
        })
      }
    }
  },

  computed: {
    isPostPaid () {
      return (this.form1Data.payMode === 2 && this.form1Data.storePayMode === 1) || (this.form1Data.payMode === 1 && !this.parentIsPostPaid)
    },
    str () {
      return this.strFlag === 1 ? '编辑' : '保存'
    },
    StorePayMode () {
      return this.form1Data.storePayMode
    },
    payMode () {
      return this.form1Data.payMode
    }
  },

  data () {
    return {
      LowWarnValues,
      currentPayType: null,
      ElemeterPayMode: ElemeterPayMode,
      parentIsPostPaid: false, // 默认父级付费方式为先付费
      stores: [],
      store_id: null,
      strFlag: 1,
      form1Data: {
        payMode: null,
        elePriceType: 1,
        storeElePrice: 0,
        storeOverdraft: 0,
        storeLowWarn: 0
      },

      parentOverdraftAmountValue: null,
      parentLowWarnValue: null,

      saveOldData: {}, // 保存初始门店配置
      form1Rules: {},

      elePriceTypes: [],
      payModes: [],
      storePayModes: [ElemeterPayMode.properties[ElemeterPayMode.PREPAID], ElemeterPayMode.properties[ElemeterPayMode.POSTPAID]],

      listTypes: ListTypes,
      listType: 1,

      limit: LIMIT,
      total: 0,
      currPage: 1,
      columns: [],
      cfgList: [],
      standardData: {}
    }
  },

  mounted () {
    this.columns = this.tableHeaders(2)

    dataCenter.getStores(this, (res, err) => {
      if (err || !res) {
        return
      }
      if (res.length) {
        this.stores = res
        this.store_id = res[0].id
        this.loadSettingInfo()
        this.loadSettingList()
      }
    })
  },

  methods: {
    formatInput (newVal) {
      if (newVal < 0) {
        return 1
      } else {
        return newVal
      }
    },
    resetAll () {
      // 回滚之前的配置
      this.form1Data = Object.assign({}, this.saveOldData)
      this.strFlag = 1
    },
    changeState () {
      // 修改按钮状态并且看按钮状态考虑是否保存
      if (this.strFlag === 1) this.strFlag = 2
      else this.saveStoreCfg('form1') // 保存门店指导配置
    },
    renderStr (key, row, type) {
      let style = {}
      let standardVal
      let storeVal
      let text
      const data = {
        ele_price: this.form1Data.storeElePrice,
        pay_type: this.form1Data.storePayMode,
        overdraft_amount: this.form1Data.storeOverdraft,
        low_warn: this.form1Data.storeLowWarn
      }
      if (type === 1) {
        standardVal = data[key]
        storeVal = row[key]
        text = storeVal ? (storeVal === 1 ? '预付费' : '后付费') : '-'
      } else {
        standardVal = Number(data[key])
        storeVal = Number(row[key])
        text = row[key] ? storeVal.toFixed(4) : '-'
      }
      if (text !== '-' && standardVal !== storeVal) {
        style.color = 'red'
        style.fontWeight = '600'
      }
      return ['span', { style }, text]
    },
    loadSettingInfo () {
      this.parentIsPostPaid = false // 初始化parentIsPostPaid
      this.currentPayType = null // 初始化currentPayType
      http.request(this, api.branch_elemeter_setting_info, [this.store_id], null, (res, err) => {
        if (err || !res) {
          return
        }

        // test
        // res = {
        //     ele_price:{
        //         parent_value:'0.0000'
        //     },
        //     overdraft_amount:{
        //         parent_value:'0.0000'
        //     },
        //     low_warn:{
        //         parent_value:0
        //     },
        //     pay_type:{
        //         parent_value:0
        //     },
        // }

        // if(res.pay_type && res.pay_type.parent_value == 0){
        //     res.pay_type.parent_value = 2
        // }
        let { pay_type, overdraft_amount, low_warn } = res // 获取付费模式,透支额度，断点提醒

        this.parentOverdraftAmountValue = +overdraft_amount.parent_value
        this.parentLowWarnValue = +low_warn.parent_value

        // 电价 ----------

        let elePriceTypes = []

        if (res.ele_price) {
          if (res.ele_price.parent_value) {
            elePriceTypes.push({ id: 1, text: `公司指导电价:${res.ele_price.parent_value}元/度` })
            this.form1Data.elePriceType = 1
          } else {
            elePriceTypes.push({ id: 1, text: '公司指导电价:未设定' })
          }

          if (res.ele_price.value) {
            elePriceTypes.push({ id: 2, text: '门店独立电价' })
            this.form1Data.elePriceType = 2
            this.form1Data.storeElePrice = Number(res.ele_price.value)
          } else {
            elePriceTypes.push({ id: 2, text: '门店独立电价' })
          }
        } else {
          elePriceTypes.push({ id: 1, text: '公司指导电价：未设定' }, { id: 2, text: '门店独立电价' })
        }
        this.elePriceTypes = elePriceTypes

        // 付费模式 ----------

        this.payModes = [
          {
            type: 1,
            text: '公司指导:'
          },
          {
            type: 2,
            text: '门店自定义'
          }
        ]

        this.payModes[0].text += pay_type.parent_value ? (pay_type.parent_value === 1 ? '预付费' : '后付费') : '未设置'

        if (pay_type.value) {
          // 如果存在自己的付费方式

          this.currentPayType = pay_type.value
          this.$set(this.form1Data, 'payMode', 2)
          this.$set(this.form1Data, 'storePayMode', pay_type.value)
        } else {
          // 沿用父级的付费模式

          if (pay_type.parent_value === 2) {
            // 父级付费模式为后付费
            this.parentIsPostPaid = true
          }

          this.parentIsPostPaid ? (this.currentPayType = 2) : (this.currentPayType = 1)
          this.$set(this.form1Data, 'payMode', 1)
          this.$set(this.form1Data, 'storePayMode', pay_type.parent_value)
        }

        // 透支额度 ----------

        this.$set(this.form1Data, 'storeOverdraft', Number(overdraft_amount.value || overdraft_amount.parent_value))

        // 低电提醒 ----------

        this.$set(this.form1Data, 'storeLowWarn', Number(low_warn.value || low_warn.parent_value))

        this.saveOldData = Object.assign({}, this.form1Data)
      })
    },

    loadSettingList () {
      http.request(this, api.branch_elemeter_setting_list, [this.store_id], _params, (res, err) => {
        if (err || !res) {
          return
        }

        this.total = res.count
        this.cfgList = res.rows.map(item => {
          const { elemeter_setting: setting } = item
          return {
            ...item,
            ele_price: (setting && setting.ele_price) || '',
            low_warn: (setting && setting.low_warn) || '',
            overdraft_amount: (setting && setting.overdraft_amount) || '',
            pay_type: (setting && setting.pay_type) || ''
          }
        })
      })
    },

    saveStoreCfg (form) {
      let { payMode, storePayMode, elePriceType, storeElePrice, storeOverdraft, storeLowWarn } = this.form1Data

      if (elePriceType === 2 && !storeElePrice) {
        this.$Message.info('门店电价设置错误')
        return
      }
      if (payMode === 2 && !storePayMode) {
        this.$Message.info('门店付费模式设置错误')
        return
      }
      if (payMode === 2 && storePayMode === 1 && (!storeOverdraft || storeOverdraft < 0.01)) {
        this.$Message.info('门店透支额度最少为0.01')
        return
      }
      if (payMode === 2 && storePayMode === 1 && !storeLowWarn) {
        this.$Message.info('门店断电提醒设置错误')
        return
      }

      let params = {}

      if (elePriceType && elePriceType === 2) {
        params.ele_price = storeElePrice
      }

      if (payMode === 2) {
        if (storePayMode) {
          params.pay_type = storePayMode
        }

        if (storePayMode === 1) {
          params.overdraft_amount = +storeOverdraft.toFixed(2)
          params.low_warn = storeLowWarn
        }
      }

      this.$refs[form].validate(valid => {
        if (!valid) {
          return
        }
        if (params.ele_price > 5) {
          this.$Message.info('电价设置最大不能超过5元')
          return
        }
        http.request(this, api.branch_elemeter_setting_update, [this.store_id], params, (res, err) => {
          if (err || !res) {
            return
          }

          this.$Message.success('保存成功')
          this.loadSettingInfo()
          this.strFlag = 1
        })
      })
    },

    selectStore (id) {
      if (id) {
        _params.offset = 0
        this.currPage = 1
        this.loadSettingInfo()
        this.loadSettingList()
      }
    },

    selectListType (type) {
      if (this.store_id) {
        _params.offset = 0
        _params.type = type
        this.columns = this.tableHeaders(type + 1)
        this.currPage = 1
        this.loadSettingList()
      }
    },

    exportList () {
      http.exportTable(this, api.branch_config_export, [this.store_id], null)
    },

    onPageChange (page) {
      _params.offset = (page - 1) * LIMIT
      this.loadSettingList()
    }
  }
}
</script>

<style lang="less" scoped>
.form-item {
    margin-bottom: 15px;
}

.list-tab {
    margin: 10px 0 0;
}
.space {
    width: 10px;
}
.table {
    margin: 10px 0;
}
.btn-left {
    margin-left: 10px;
}
</style>
